package com.jeecms.wicool.action.shops;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.wicool.entity.cms.CmsInfo;
import com.jeecms.wicool.entity.shops.PayType;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.cms.CmsInfoMng;
import com.jeecms.wicool.manager.shops.WiPayTypeMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jeecms.common.page.SimplePage.cpn;

/**
 * 商铺Action
 */
@Controller
public class WiShopInfoAct {
    private static final Logger log = LoggerFactory.getLogger(WiShopInfoAct.class);

    @RequestMapping("/shops/v_list.do")
    public String list(Integer pageNo,
                       HttpServletRequest request, ModelMap model) {
        Pagination pagination = manager.getPage(cpn(pageNo),
                CookieUtils.getPageSize(request), CmsUtils.getUser(request));

        List<ShopInfo> listShopInfo = (List<ShopInfo>) pagination.getList();
        List<Dictionary2> listDic = DicMng.getList("shop_type");
        Map<String, String> map = new HashMap<String, String>();
        for (Dictionary2 d : listDic) {
            map.put(d.getDicCode().toString(), d.getDicName());
        }
        for (ShopInfo p : listShopInfo) {
            if (map.containsKey(p.getShopType().toString())) {
                p.setShopTypeName(map.get(p.getShopType().toString()));
            }
        }
        model.addAttribute("pagination", pagination);

        return "shops/list_shops";
    }

    /**
     * 支付方式列表
     *
     * @param pageNo
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/shops/v_list_payType.do")
    public String listPayType(Integer pageNo,
                              HttpServletRequest request, ModelMap model) {
        Pagination pagination = payTypeMng.getPage(cpn(pageNo),
                CookieUtils.getPageSize(request), CmsUtils.getUser(request));
        List<PayType> listPayType = (List<PayType>) pagination.getList();
        List<Dictionary2> listDic = DicMng.getList("pay_type");
        List<ShopInfo> listShop = manager.getAll(CmsUtils.getUser(request));
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String> mapShop = new HashMap<String, String>();
        for (Dictionary2 d : listDic) {
            map.put(d.getDicCode().toString(), d.getDicName());
        }
        for (ShopInfo s : listShop) {
            mapShop.put(s.getId().toString(), s.getShopName());
        }
        for (PayType p : listPayType) {
            if (map.containsKey(p.getPayType().toString())) {
                p.setPayTypeName(map.get(p.getPayType().toString()));
            }
            if (mapShop.containsKey(p.getShopId().toString())) {
                p.setShopName(mapShop.get(p.getShopId().toString()));
            }
        }
        model.addAttribute("pagination", pagination);

        return "shops/list_payType";
    }


    @RequestMapping("/shops/v_edit.do")
    public String edit(Integer id, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateEdit(id, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        ShopInfo shopInfo = manager.findById(id);
        List<Dictionary2> listShopType = DicMng.getList("shop_type");

        //根据规则获取店铺微信 url 和 token
        String token = getWeiXinTokenMd5(shopInfo.getShopWeixinId());
        String url = getWeiXinUrlMd5(shopInfo.getId().toString());

        model.addAttribute("shopInfo", shopInfo);
        model.addAttribute("listShopType", listShopType);
        model.addAttribute("token", token);
        model.addAttribute("url", url);
        return "shops/edit_shops";
    }

    public String getWeiXinTokenMd5(String shopWeixinId) {
        String key = "wicool-weixin-md5" + "%#$";
        String md5Code = DigestUtils.md5Hex(shopWeixinId + key);
        return md5Code;
    }

    public String getWeiXinUrlMd5(String id) {
        String key = "wicoolshop" + (860330 + id);
        String s = "http://115.28.223.55/vshop/weixin/token.do?uk=";
        return s + key;
    }

    @RequestMapping("/shops/o_update.do")
    public String update(ShopInfo bean, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateUpdate(bean.getId(), request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = simpleTime.format(new Date());
        Timestamp t = Timestamp.valueOf(dateTime);

        bean.setUpdateTime(t);
        String preDetailURLPrefix = manager.findById(bean.getId()).getDetailPageURL();//修改前的URL前缀
        bean = manager.update(bean);
        String currentDetailUrlPrefix = bean.getDetailPageURL();//修改后的URL前缀

        //如果URL前缀有过修改，则更新所有首页发布地址
        if (!Objects.equals(preDetailURLPrefix, currentDetailUrlPrefix)) {
            updateDetailPageInfo(bean.getId(), CmsUtils.getUser(request), preDetailURLPrefix, currentDetailUrlPrefix);
        }


        model.addAttribute("message", "global.success");
        log.info("update ShopInfo success. id={}", bean.getId());
        cmsLogMng.operating(request, "shop.log.update", "id=" + bean.getId());
        return edit(bean.getId(), request, model);
    }

    private void updateDetailPageInfo(Integer shopId, CmsUser user, String preDetailURLPrefix, String currentDetailUrlPrefix) {
        List<CmsInfo> cmsInfos = cmsInfoMng.getAll(user);
        for (CmsInfo cmsInfo : cmsInfos) {
            String newPath = cmsInfo.getCmsPath().replaceAll(preDetailURLPrefix, currentDetailUrlPrefix);
            cmsInfo.setCmsPath(newPath);

            cmsInfoMng.update(cmsInfo, shopId);
        }
    }

    /**
     * 添加支付方式
     *
     * @param model
     * @return
     */
    @RequestMapping("/shops/v_add_payType.do")
    public String addPayType(ModelMap model, HttpServletRequest request) {
        //获取到所有店铺集合
        List<ShopInfo> listShopInfo = manager.getAll(CmsUtils.getUser(request));
        //获取数据字段中支付方式集合
        List<Dictionary2> listShopType = DicMng.getList("pay_type");
        model.addAttribute("listShopInfo", listShopInfo);
        model.addAttribute("listShopType", listShopType);
        return "shops/add_payType";
    }

    /**
     * 支付方式保存
     *
     * @param bean
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/shops/o_save_payType.do")
    public String save(PayType bean, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateSave(bean, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        //验证同一个商铺下只能有一个支付方式
        List<PayType> payTypeList = payTypeMng.getPayTypeList(bean.getShopId());
        for (PayType p : payTypeList) {
            if (p.getPayType().equals(bean.getPayType())) {
                model.addAttribute("msg", "同一个商铺下只能有一个支付方式");
                return "common/error_message2";
            }
        }


        bean = payTypeMng.save(bean);
        log.info("save PayType id={}", bean.getId());
        cmsLogMng.operating(request, "PayType.log.save", "id="
                + bean.getId() + ";shopId=" + bean.getShopId());
        return "redirect:v_list_payType.do";
    }

    /**
     * 支付方式修改
     *
     * @param id
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/shops/v_edit_payType.do")
    public String editPayType(Integer id, HttpServletRequest request, ModelMap model) {
//		WebErrors errors = validateEdit(id, request);
//		if (errors.hasErrors()) {
//			return errors.showErrorPage(model);
//		}
        PayType payType = payTypeMng.findById(id);
        List<Dictionary2> listPayType = DicMng.getList("pay_type");
        //获取该店铺已经存在的支付方式
        List<PayType> payTypeList = payTypeMng.getPayTypeList(payType.getShopId());
        for (PayType p : payTypeList) {
            listPayType.remove(DicMng.findByDicCode("pay_type", p.getPayType().shortValue()));
        }

        List<ShopInfo> listShopInfo = manager.getAll(CmsUtils.getUser(request));

        model.addAttribute("payType", payType);
        model.addAttribute("listPayType", listPayType);
        model.addAttribute("listShopInfo", listShopInfo);
        return "shops/edit_payType";
    }

    /**
     * 支付方式更新
     *
     * @param bean
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/shops/o_update_payType.do")
    public String updatePayType(PayType bean, HttpServletRequest request, ModelMap model) {
        WebErrors errors = validateUpdate(bean.getId(), request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        //验证同一个商铺下只能有一个支付方式
        List<PayType> payTypeList = payTypeMng.getPayTypeList(bean.getShopId());
        for (PayType p : payTypeList) {
            if (p.getPayType().equals(bean.getPayType())) {
                model.addAttribute("msg", "同一个商铺下只能有一个支付方式");
                return "common/error_message2";
            }
        }
        SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = simpleTime.format(new Date());
        Timestamp t = Timestamp.valueOf(dateTime);

        bean.setUpdateTime(t);
        bean = payTypeMng.update(bean);
        model.addAttribute("message", "global.success");
        log.info("update PayInfo success. id={}", bean.getId());
        cmsLogMng.operating(request, "PayType.log.update", "id=" + bean.getId());
        return editPayType(bean.getId(), request, model);
    }

    @RequestMapping("/shops/o_delete.do")
    public String delete(Integer[] ids, Integer pageNo, HttpServletRequest request,
                         ModelMap model) {
        WebErrors errors = validateDelete(ids, request);
        if (errors.hasErrors()) {
            return errors.showErrorPage(model);
        }
        ShopInfo[] beans = manager.deleteByIds(ids);
        for (ShopInfo bean : beans) {
            log.info("delete ShopInfo id={}", bean.getId());
            cmsLogMng.operating(request, "shop.log.delete", "id="
                    + bean.getId() + ";name=" + bean.getName());
        }
        return list(pageNo, request, model);
    }

    @RequestMapping("/shops/o_delete_payType.do")
    public String deletePayType(Integer[] ids, Integer pageNo, HttpServletRequest request,
                                ModelMap model) {
        PayType[] beans = payTypeMng.deleteByIds(ids);
        for (PayType bean : beans) {
            log.info("delete PayType id={}", bean.getId());
            cmsLogMng.operating(request, "PayType.log.delete", "id="
                    + bean.getId() + ";name=" + bean.getPayTypeName());
        }
        return listPayType(pageNo, request, model);
    }

    @RequestMapping("/shops/check_payType.do")
    public void checkPayType(HttpServletRequest request, HttpServletResponse response, String payType, String shopId) throws Exception {
        JSONArray result = new JSONArray();
        JSONObject obj = null;
        List<PayType> payTypeList = new ArrayList<PayType>();
        payTypeList = payTypeMng.getPayTypeList(Integer.parseInt(shopId));
        if (payTypeList.size() != 0) {
            for (PayType p : payTypeList) {
                if (p.getPayType().equals(payType)) {
                    obj.put("flag", false);
                    break;
                } else {
                    obj.put("flag", true);
                }
            }
        } else {
            obj.put("flag", false);
        }

        ResponseUtils.renderJson(response, obj.toString());
    }

    private WebErrors validateSave(PayType bean, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        return errors;
    }

    private WebErrors validateEdit(Integer id, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        if (vldExist(id, errors)) {
            return errors;
        }
        return errors;
    }

    private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        if (vldExist(id, errors)) {
            return errors;
        }
        // TODO 验证是否为管理员，管理员不允许修改。
        return errors;
    }

    private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
        WebErrors errors = WebErrors.create(request);
        errors.ifEmpty(ids, "ids");
        for (Integer id : ids) {
            vldExist(id, errors);
        }
        return errors;
    }

    private boolean vldExist(Integer id, WebErrors errors) {
        if (errors.ifNull(id, "id")) {
            return true;
        }
        ShopInfo entity = manager.findById(id);
        if (errors.ifNotExist(entity, ShopInfo.class, id)) {
            return true;
        }
        return false;
    }

    @Autowired
    private WiShopInfoMng manager;
    @Autowired
    private WiPayTypeMng payTypeMng;
    @Autowired
    private CmsLogMng cmsLogMng;
    @Autowired
    private DictionaryMng DicMng;

    @Autowired
    private CmsInfoMng cmsInfoMng;

}
